package com.information.manage.common.constants;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;

public enum DataType {

    NONE("none"),
    STRING("String"),
    LIST("List"),
    SET("Set"),
    DATE("Date"),
    DATEANDTIME("DateAndTime"),
    LOCALDATE("LocalDate");
    ;

    private String code;

    DataType(String code){
        this.code = code;
    }

    public static Object convertValue(String value, DataType dataType) {
        switch (dataType) {
            case NONE:
                return null;
            case STRING:
                return value;
            case LIST:
                // 假设列表格式是逗号分隔的字符串
                return Arrays.asList(value.split(","));
            case SET:
                // 假设集合格式是逗号分隔的字符串
                return new HashSet<>(Arrays.asList(value.split(",")));
            case DATE:
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    return dateFormat.parse(value);
                } catch (ParseException e) {
                    dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                    try {
                        return dateFormat.parse(value);
                    } catch (ParseException ex) {
                        throw new IllegalArgumentException("Invalid date format: " + value, e);
                    }
                }
            case DATEANDTIME:
                SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    return datetimeFormat.parse(value);
                } catch (ParseException e) {
                    datetimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                    try {
                        return datetimeFormat.parse(value);
                    } catch (ParseException ex) {
                        throw new IllegalArgumentException("Invalid datetime format: " + value, e);
                    }
                }
            case LOCALDATE:
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
                try {
                    LocalDate date = LocalDate.parse(value, formatter);
                    LocalDateTime dateTime = LocalDateTime.of(date, LocalTime.MIDNIGHT);
                    return dateTime;
                } catch (DateTimeParseException e) {
                    throw new IllegalArgumentException("Invalid LocalDate format: " + value, e);
                }
            default:
                throw new IllegalArgumentException("Unsupported data type: " + dataType);
        }
    }

}
